﻿using System.Text;
using System.Web.Routing;
using SlamCms.Common;
using SlamCms.Configuration;
using SlamCms.Web;

namespace System.Web.Mvc
{
	public static class SlamCmsUrlHelper
	{
		static SlamCmsUrlHelper()
		{
			ContentBaseUrl = "~";
			ContentFolder = "Content";
			StylesFolder = "Styles";
			ImagesFolder = "Images";
			ScriptsFolder = "Scripts";
		}

		public static string ContentBaseUrl { get; set; }
		public static string ContentFolder { get; set; }
		public static string StylesFolder { get; set; }
		public static string ImagesFolder { get; set; }
		public static string ScriptsFolder { get; set; }

		public static string GetBaseUrl()
		{
			var uriService = DependencyResolver.Current.GetService<IBaseUriResolver>();
			return uriService.GetBaseUri().ToString();
		}

		public static string GetImageUrl(string fileName)
		{
			return GetUrl(ImagesFolder, fileName);
		}

		public static string GetStyleUrl(string fileName)
		{
			if (!fileName.EndsWith(".css") && !fileName.Contains("?"))
				fileName += ".css";

			return GetUrl(StylesFolder, fileName);
		}

		public static string GetScriptUrl(string fileName)
		{
			if (!fileName.EndsWith(".js") && !fileName.Contains("?"))
				fileName += ".js";

			return GetUrl(ScriptsFolder, fileName);
		}

		private static string GetUrl(string folder, string fileName)
		{
			if (fileName.StartsWith("http"))
				return fileName;

			if (!fileName.StartsWith("~"))
				fileName = "{0}/{1}/{2}/{3}".F(ContentBaseUrl, ContentFolder, folder, HttpUtility.HtmlAttributeEncode(fileName));

			return VirtualPathUtility.ToAbsolute(fileName);
		}

		public static string AdminRedirector(string to, string slamId = null, object routeValues = null, string returnUrl = null)
		{
			var adminUrl = ConfigurationManager.Environment.DefaultApplication.AdminUrl.TrimEnd('/');
			return "{0}/{1}".F(adminUrl, AdminRedirectorRelative(to, slamId, routeValues, returnUrl));
		}

		public static string AdminRedirectorRelative(string to, string slamId = null, object routeValues = null, string returnUrl = null)
		{
			var sb = new StringBuilder();
			sb.Append("_layouts/SlamCMS/Redirector.aspx?to={0}".F(to));

			if (!slamId.IsNullOrWhiteSpace())
				sb.Append("&slamId={0}".F(HttpUtility.UrlEncode(slamId)));

			var routeValueDictionary = new RouteValueDictionary(routeValues);
			foreach (var routeValue in routeValueDictionary)
			{
				sb.Append("&{0}={1}".F(HttpUtility.UrlEncode(routeValue.Key), HttpUtility.UrlEncode(routeValue.Value.ToString())));
			}

			string encodedReturnUrl;
			if (returnUrl.IsNullOrWhiteSpace())
				encodedReturnUrl = HttpContext.Current != null ? HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl) : string.Empty;
			else
				encodedReturnUrl = HttpUtility.UrlEncode(returnUrl);

			sb.Append("&returnUrl={0}".F(encodedReturnUrl));

			return sb.ToString();
		}
	}
}